import java.io.File;

public class ExeExecutor {

    private static final String EXE_FILE_PATH = "pngcrush.exe";
    private static final String RESULT_DIR = "Crushed";

    public static void crushFile(String inputFilePath) {
        File inputFile = new File(inputFilePath);
        if (inputFile != null && inputFile.exists()) {
            File outputFile = new File(inputFile.getParentFile().getAbsolutePath() + File.separator + RESULT_DIR);
            if (!outputFile.exists()) {
                outputFile.mkdirs();
            } else if (outputFile.isFile()) {
                outputFile.delete();
                outputFile.mkdirs();
            }
            if (inputFile.isDirectory()) {
                crushFolderFile(inputFile.getAbsolutePath(), inputFile.getAbsolutePath(), outputFile.getAbsolutePath());
            } else {
                outputFile = new File(inputFile.getParentFile().getAbsolutePath() + File.separator + RESULT_DIR + File.separator + inputFile.getName());
                System.out.println(outputFile.getAbsolutePath());
                crushSingleFile(inputFilePath, outputFile.getAbsolutePath());
            }
        } else {
            return;
        }
    }

    private static void crushFolderFile(String fixedInputFolder, String inputFolder, String outputFolder) {
        File inputFile = new File(inputFolder);
        File outputFile = new File(outputFolder);
        File[] files = inputFile.listFiles();
        if (null == files || files.length == 0) {
            return;
        } else {
            for (File file : files) {
                if (file.isDirectory()) {
                    crushFolderFile(fixedInputFolder, file.getAbsolutePath(), outputFolder);
                } else {
                    crushSingleFile(file.getAbsolutePath(), outputFile.getAbsolutePath() + file.getAbsolutePath().replace(fixedInputFolder, ""));
                }
            }
        }
    }

    private static void crushSingleFile(String inputFilePath, String outputFilePath) {
        try {
            File outputFile = new File(outputFilePath).getParentFile();
            if (!outputFile.exists()) {
                outputFile.mkdirs();
            } else if (outputFile.isFile()) {
                outputFile.delete();
                outputFile.mkdirs();
            }
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(EXE_FILE_PATH + " \"" + inputFilePath + "\" " + "\"" + outputFilePath + "\"");
            System.out.println("输入文件：" + " " + inputFilePath + " ,大小为：" + new File(inputFilePath).length() / 1024 + "KB");
            process.waitFor();
            System.out.println("输出文件：" + " " + outputFilePath + " ,大小为：" + new File(outputFilePath).length() / 1024 + "KB");
            System.out.println("输=========================");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
